function countingSort(array) {
    if (array.length < 2) {
      return array
    }
    const maxValue = findMaxValue(array)
    const counts = new Array(maxValue + 1)
    array.forEach(item => {
      if (!counts[item]) {
        counts[item] = 0
      }
      counts[item]++
    })
    let sortIndex = 0
    counts.forEach((item, index) => {
      while (item > 0) {
        array[sortIndex++] = index
        item--
      }
    })
    return array
  }
  function findMaxValue(array) {
    let max = array[0]
    for (let index = 1; index < array.length; index++) {
      if (array[index] > max) {
        max = array[index]
      }
    }
    return max
}


const result = countingSort([5, 4, 3, 2, 1])
console.log(result) // [1, 2, 3, 4, 5]
